<?php
namespace app\admin\controller;
use app\admin\model\GoodsComment;
use app\admin\model\GoodsModel;
use app\admin\model\UserModel;
use think\Controller;
use think\Db;
use think\Paginator;
use think\Request;

// 商品控制
class PcGoods extends Common
{
    const PLAT_ID = 2;
    // 查看全部商品列表
    public function getGoodsList(Request $request)
    {

        $goods_cate = $request->param('goods_cate',0);

        $query = GoodsModel::getGoodsListQuery($goods_cate,self::PLAT_ID);
        
        $list = $query->order('goods_id desc')->paginate(5);
       
        $this->assign('goods_amount', GoodsModel::getGoodsCount($goods_cate,self::PLAT_ID));
        $this->assign('page', $list->render());
        $this->assign('list', $list);
        $this->assign('cate_list',GoodsModel::getGoodsCateList(self::PLAT_ID));
        $this->assign('goods_cate',$goods_cate);
        return $this->fetch('pcgoods/goods');
    }



    // 新上架商品
    public function getAddGoods(){

        $this->assign('cate_list',GoodsModel::getGoodsCateList(self::PLAT_ID));
        //$this->assign('plat_list',GoodsModel::getPlatList(self::PLAT_ID));
        return $this->fetch('pcgoods/add');
    }

    // 
    public function postAddGoods(Request $request){

        if($request->isPost()){
            $post_data = $request->post();


           if(empty($post_data['goods_name'])){
              $this->error('商品名称不能为空','/PcGoods/AddGoods');
            }
//            if(empty($post_data['price'])) {
//                $this->error('商品价格不能为空', '/Goods/AddGoods');
//            }
            if (empty($post_data['stock'])) {
                $this->error('当前库存不能为空', '/PcGoods/AddGoods');
            }

            
//            if(empty($post_data['plats'])){
//                $this->error('指定发布平台', '/Goods/AddGoods');
//            }

            $goods_info = [
                'goods_name'=>$post_data['goods_name'],
                'goods_sn'=>$post_data['goods_sn'],
                'price'=>$post_data['price'],
                'stock'=>$post_data['stock'],
                'goods_cate'=>$post_data['goods_cate'],
                'goods_type'=>$post_data['goods_type'],
                'formal_price'=>$post_data['formal_price'],
                'describe'=>nl2br(str_replace("\r\n","\n",$post_data['describe'])),
                'goods_points'=>$post_data['points_num'],
                'is_show'=>$post_data['is_show'],
                'goods_plat'=>self::PLAT_ID
            ];
            // 商品图片
            $file=$request->file('goods_img');
            if($file){
                
                $goods_info['goods_img'] =  handle_upload_image($file,GoodsModel::GOODS_IMAGE_PATH);
                
            } else {
                $goods_info['goods_img'] = 'default.jpg';

            }

            $bool = Db::table('goods')->insert($goods_info);

            if ($bool) {
               $this->success('添加成功', '/PcGoods/GoodsList');
            } else {
               $this->error('添加失败', '/PcGoods/AddGoods');
            }
        }
        

    }


    // 商品信息修改
    public function getEditGoods(Request $request){
        
        $id=$request->param('id');


        $goodsInfo=GoodsModel::getGoodsInfoById($id);

        $goodsInfo['goods_img']=get_image_url(GoodsModel::GOODS_IMAGE_PATH,$goodsInfo['goods_img']);
        $goodsInfo['describe']=str_replace("<br />","\n",$goodsInfo['describe']);
        $this->assign('cate_list',GoodsModel::getGoodsCateList(self::PLAT_ID));
       // $this->assign('plat_list',GoodsModel::getPlatList());
        $this->assign('goods_plat_list',GoodsModel::getPlatInfo($goodsInfo['goods_plat'],true));
        return $this->fetch('pcgoods/edit',['info'=>$goodsInfo]);
    }

    public function postEditGoods(Request $request){
        // 更新商品信息
        if($request->isPost()){
            $post_data=$request->post();

//            if(empty($post_data['plats'])){
//                $this->error('指定发布平台', '/Goods/AddGoods');
//            }
            $goods_info = [
                'goods_name'=>$post_data['goods_name'],
                'goods_sn'=>$post_data['goods_sn'],
                'price'=>$post_data['price'],
                'stock'=>$post_data['stock'],
                'goods_cate'=>$post_data['goods_cate'],
                'goods_type'=>$post_data['goods_type'],
                'formal_price'=>$post_data['formal_price'],
                'describe'=>nl2br(str_replace("\r\n","\n",$post_data['describe'])),
                'goods_points'=>$post_data['points_num'],
                'is_show'=>$post_data['is_show'],
                'goods_plat'=>self::PLAT_ID
            ];

            $file=$request->file('goods_img');
            $change_img =false;
            if($file){

                $change_img =true;
                $goods_info['goods_img'] =  handle_upload_image($file,GoodsModel::GOODS_IMAGE_PATH);
                // 原来图片地址
                $oldImgPath= GoodsModel::getGoodsInfoById($post_data['goods_id'],'goods_img');

            }

            $res = Db::table('goods')->where(['goods_id'=>$post_data['goods_id']])
                 ->update($goods_info);

            if ($res) {
                if($change_img && $oldImgPath['goods_img'] != 'default.jpg'){
                    unlink(get_image_url(GoodsModel::GOODS_IMAGE_PATH,$oldImgPath['goods_img'],false));
                }

               $this->success('修改成功', '/PcGoods/GoodsList');
            } else {
                 $this->error('修改失败', "/PcGoods/EditGoods/id/{$post_data['goods_id']}");
            }

        }

        

    }


    // Ajax 下架 下架切换
    public function postAjaxWithdrawGoods(Request $request){

        if($request->isAjax()){
            $is_show = $request->param('is_show');
            $goods_id=$request->param('goods_id');


            return GoodsModel::updateGoodsStatus($is_show,$goods_id);

        }else{
            return false;
        }
    }
    //修改积分数
     public function postAjaxChangePointsNum(Request $request)
     {
         $goods_id =$request->post('goods_id');
         $points_num = $request->post('points_num');
         if(!is_numeric($goods_id))
         {
             die(json_encode(false));
         }

         GoodsModel::updateGoodsPoints($goods_id,$points_num);
         die(json_encode(true));
     }
    // 删除商品信息
    public function postDelGoods(Request $request){
        $id=$request->post('id');

        $res=GoodsModel::delGoodsInfo($id);

        return $res;
    }

    //添加 商品 分类
    public function getEditGoodsCate(Request $request)
    {
        $id=$request->param('cate_id',0);

        if($id == 0)
        {
            $cate_info = [
                'cate_id'=>'',
                'cate_name'=>'',
                'cate_order'=>'',

            ];

        }else{
            $cate_info = GoodsModel::getGoodsCateInfo($id);
          //  $this->assign('cate_plat_list',GoodsModel::getPlatInfo($cate_info['cate_plat'],true));

        }
        //$this->assign('plat_list',GoodsModel::getPlatList());

        return $this->fetch('pcgoods/edit_cate',['info'=>$cate_info]);
    }

    public function postEditGoodsCate(Request $request){
        // 更新商品信息

        $goods_cate_id = $request->post('goods_cate_id',0);
        $goods_cate_name = $request->post('cate_name');
        $goods_cate_order = $request->post('cate_order');
       // $cate_plat_list = $request->post('plats/a');

      //  $cate_plat_num = GoodsModel::calcPlatNum($cate_plat_list);

        GoodsModel::updateGoodsCateInfo($goods_cate_id,$goods_cate_name,$goods_cate_order,self::PLAT_ID);
        $this->success('修改成功', '/PcGoods/GoodsCateList');

    }

    public function getGoodsCateList(Request $request)
    {

        $query = GoodsModel::getGoodsCateQuery(self::PLAT_ID);
        $list = $query->order('cate_order')->paginate(5);

        $this->assign('count',GoodsModel::getGoodsCateQuery(self::PLAT_ID)->count());
        $this->assign('page', $list->render());
        $this->assign('list', $list);
        return $this->fetch('pcgoods/goods_cate_list');

    }
    public function postAjaxUpdateGoodsCateOrder(Request $request)
    {
        $goods_cate_id = $request->post('goods_cate_id',0);
        $goods_cate_order = $request->post('cate_order');
        GoodsModel::updateGoodsCateInfo($goods_cate_id,'',$goods_cate_order);
        die(json_encode(true));
    }

    public function postDelGoodsCate(Request $request){
        $id=$request->post('goods_cate_id');

        return GoodsModel::deleteGoodsCate($id);
    }
    public function getCommentList(Request $request)
    {
        $keyword=$request->param('keyword');

        $order_type=$request->param('order_type',1);


        $search_type = $request->param('search_type','');
        $user_id =null;
        $goods_id =null;
        if($search_type == 'user')
        {
            $user_id = UserModel::getUserIdByUserName($keyword);
        }else if($search_type == 'goods')
        {
            $goods_id = GoodsModel::getGoodsIdByName($keyword);
        }
        $query = GoodsComment::getCommentQuery($goods_id,$user_id);

        if($order_type == 1)
        {
            $query->order('comment_time desc');
        }else{
            $query->order('comment_time');
        }
        $this->assign([
            'list'=>$query->paginate(),
            'keyword'=>$keyword,
            'order_type'=>$order_type,
            'search_type'=>$search_type,
        ]);

        return $this->fetch('commentList');
    }
    
    public function postAjaxDeleteComment(Request $request)
    {
        $id = $request->post('id');
        if(!is_numeric($id))
        {
            die(json_encode(false));
        }
        GoodsComment::deleteComment($id);
        die(json_encode(true));
    }

   
}
